package com.lanniao.controller;

import com.lanniao.dto.PageQueryDto;
import com.lanniao.dto.UserLoginDto;
import com.lanniao.entity.TbUser;
import com.lanniao.result.PageResult;
import com.lanniao.result.Result;
import com.lanniao.service.UserService;
import com.lanniao.utils.JwtUtil;
import com.lanniao.vo.TbUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Api(tags = "用户相关接口")
public class UserControler {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     * @param pageQueryDto
     * @return
     */
    @PostMapping("/page")
    @ApiOperation(value = "员工分页查询")
    public Result page(@RequestBody PageQueryDto pageQueryDto){
        PageResult pageResult = userService.pageQuery(pageQueryDto);
        return Result.success(pageResult);
    }

    /**
     * 员工登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result login(@RequestBody UserLoginDto user) {
        TbUser tbUser = userService.login(user);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userid", tbUser.getId());
        String token = JwtUtil.createJWT("key", 7200000, claims);

        TbUserVo tbUserVo = new TbUserVo();
        BeanUtils.copyProperties(tbUser, tbUserVo);
        tbUserVo.setToken(token);
        return Result.success(tbUserVo);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public Result getById(@PathVariable Integer id) {
        TbUser user = (TbUser) redisTemplate.opsForValue().get("user_id:" + id);
        if (user != null){
            return Result.success(user);
        }
        user = userService.getById(id);
        redisTemplate.opsForValue().set("user_id:"+id, user, 3L, TimeUnit.MINUTES);
        return Result.success(user);
    }

    @PutMapping
    @ApiOperation(value = "修改用户信息")
    public Result update(@RequestBody TbUser tbUser){
        userService.update(tbUser);
        return Result.success();
    }
}
